package code;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import net.rim.device.api.math.Fixed32;
import net.rim.device.api.servicebook.ServiceBook;
import net.rim.device.api.servicebook.ServiceRecord;
import net.rim.device.api.system.Bitmap;
import net.rim.device.api.system.DeviceInfo;
import net.rim.device.api.system.EncodedImage;
import net.rim.device.api.system.RadioException;
import net.rim.device.api.system.RadioInfo;
import net.rim.device.api.system.WLANInfo;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.Dialog;

public class Function
{
	public static String getIP()// throws RadioException
	{
		int apnId;
		String ip = "";

		try {
			apnId = RadioInfo.getAccessPointNumber("MagicRudyAPN.rim");
			byte[] ipByte = RadioInfo.getIPAddress(apnId);
			
			for (int i = 0; i < ipByte.length; i++) {
				int temp = (ipByte[i] & 0xff);
				if (i < 3)
					ip = ip.concat("" + temp + ".");
				else {
					ip = ip.concat("" + temp);					
				}
			}
		} catch (RadioException e) {}
		
		return ip;
	}

	public static String readStream(InputStream is) throws IOException
	{
		String result = new String();
		char[] buffer = new char[256];
		//long cursor = 0;
		int offset = 0;
		
		InputStreamReader br = new InputStreamReader(is, "UTF-8");

		while((offset=br.read(buffer))!=-1)
		{
			result += new String(buffer, 0, offset);
			//cursor += offset;
		}
		is.close();
		
		return result;
	}

    public static void errorDialog(final String message)
    {
        UiApplication.getUiApplication().invokeAndWait(new Runnable()
        {
            public void run()
            {
                Dialog.alert(message);
            } 
        });
    }
    
	public static String updateConnectionSuffix()
	{
		String connSuffix = null;
		
		if(DeviceInfo.isSimulator())
		{
			connSuffix = ";deviceside=true";
		//} else {
		//	connSuffix=";ConnectionUID=GTCP BISB";
		}
		else {
			if((WLANInfo.getWLANState() == WLANInfo.WLAN_STATE_CONNECTED) && RadioInfo.areWAFsSupported(RadioInfo.WAF_WLAN))
			{
				connSuffix=";interface=wifi";
			} else {
				String uid = null;
				ServiceBook sb = ServiceBook.getSB();
				ServiceRecord[] records = sb.findRecordsByCid("WPTCP");
				
				for (int i = 0; i < records.length; i++)
				{
					if (records[i].isValid() && !records[i].isDisabled())
					{
						if (records[i].getUid() != null && records[i].getUid().length() != 0)
						{
							if ((records[i].getCid().toLowerCase().indexOf("wptcp") != -1) &&
									(records[i].getUid().toLowerCase().indexOf("wifi") == -1) &&
									(records[i].getUid().toLowerCase().indexOf("mms") == -1) )
							{
								uid = records[i].getUid();
								break;
							}
						}
					}
				}
				
				if (uid != null)
				{
					// WAP2 Connection
					connSuffix = ";ConnectionUID="+uid;
				} else {
					connSuffix = ";deviceside=true";
				}
			}
		} 
		
		return connSuffix;
	}
	
	public static Bitmap bestFit(EncodedImage image, int maxWidth, int maxHeight)
	{
		int w = image.getWidth();
		int h = image.getHeight();
		
		if(w<=maxWidth && h<=maxHeight) {return image.getBitmap();}
		
		int ratiow = 10000 * maxWidth / w;
		int ratioh = 10000 * maxHeight / h;
		
		int ratio = ratioh;//Math.min(ratiow, ratioh);
		
		int desiredWidth = w * ratio / 10000;
		int desiredHeight = h * ratio / 10000;
		
		//return setSizeImage(image, desiredWidth, desiredHeight);
		return GPATools.ResizeTransparentBitmap(image.getBitmap(), desiredWidth, desiredHeight, Bitmap.FILTER_LANCZOS, Bitmap.SCALE_TO_FIT);
	}
	
	private static Bitmap setSizeImage(EncodedImage image, int width, int height)
	{
		EncodedImage result = null;

		int currentWidthFixed32 = Fixed32.toFP(image.getWidth());
		int currentHeightFixed32 = Fixed32.toFP(image.getHeight());

		int requiredWidthFixed32 = Fixed32.toFP(width);
		int requiredHeightFixed32 = Fixed32.toFP(height);

		int scaleXFixed32 = Fixed32.div(currentWidthFixed32, requiredWidthFixed32);
		int scaleYFixed32 = Fixed32.div(currentHeightFixed32, requiredHeightFixed32);

		result = image.scaleImage32(scaleXFixed32, scaleYFixed32);
		
		return result.getBitmap();
	}
	
	public static EncodedImage bestFitEncodedImage(EncodedImage image, int maxWidth, int maxHeight)
	{
		int w = image.getWidth();
		int h = image.getHeight();
		
		if(w<=maxWidth && h<=maxHeight) {return image;}
		
		int ratiow = 10000 * maxWidth / w;
		int ratioh = 10000 * maxHeight / h;
		
		int ratio = Math.min(ratiow, ratioh);
		
		int desiredWidth = w * ratio / 10000;
		int desiredHeight = h * ratio / 10000;
		
		return setSizeEncodedImage(image, desiredWidth, desiredHeight);
	}
	
	private static EncodedImage setSizeEncodedImage(EncodedImage image, int width, int height)
	{
		EncodedImage result = null;

		int currentWidthFixed32 = Fixed32.toFP(image.getWidth());
		int currentHeightFixed32 = Fixed32.toFP(image.getHeight());

		int requiredWidthFixed32 = Fixed32.toFP(width);
		int requiredHeightFixed32 = Fixed32.toFP(height);

		int scaleXFixed32 = Fixed32.div(currentWidthFixed32, requiredWidthFixed32);
		int scaleYFixed32 = Fixed32.div(currentHeightFixed32, requiredHeightFixed32);

		result = image.scaleImage32(scaleXFixed32, scaleYFixed32);
		
		return result;
	}
}